package com.back.end.Service.impl;

import com.back.end.Dao.AppProductDao;
import com.back.end.Modal.ProductChild;
import com.back.end.Modal.ProductList;
import com.back.end.Modal.Sales;
import com.back.end.Service.AppProductService;
import com.back.end.utils.ListToUnique;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AppProductServiceImpl implements AppProductService {
    @Resource
    AppProductDao appProductDao;

    @Override
    public List<ProductList> getProductList() {
        //从数据库获取数据，并且将商品ID，名称筛选出来放入productList列表中
        List<ProductChild> products = appProductDao.getProductList();
        List<ProductList> productList = new ArrayList<ProductList>();
        products.forEach(item -> {
            ProductList product = new ProductList();
            product.setTypeId(item.getTypeId());
            product.setType(item.getType());
            productList.add(product);
        });
        ListToUnique listToUnique = new ListToUnique();
        List<ProductList> finalProductList = listToUnique.toUnique(productList);

        //将数据库获取的数据根据商品ID分类
        for (ProductList productListChild : finalProductList) {
            for (ProductChild product : products) {
                //构造新商品列表
                List<ProductChild> list = new ArrayList<>();
                if (productListChild.getTypeId() == product.getTypeId()) {
                    list.add(product);
                    if (productListChild.getProducts() != null) {
                        list.addAll(productListChild.getProducts());
                        productListChild.setProducts(list);
                    } else {
                        productListChild.setProducts(list);
                    }
                }
            }
        }
        return finalProductList;
    }

    @Override
    public ProductChild getProductChildById(int id) {
        ProductChild productChild = appProductDao.getProductChildById(id);
        return productChild;
    }

    @Override
    public void updateProductChild(int id, int num) {
        appProductDao.updateProductChild(id, num);
    }

    @Override
    public void addOrdersProduct(Sales sales) {
        appProductDao.addOrdersProduct(sales);
    }

}
